import asyncio
import time
from queue import Queue
import websockets
import json
from datetime import datetime
from threading import Thread
import random

# 检测客户端权限，用户名密码通过才能退出循环
# faces = []
queue = Queue()
async def func():
    # global faces
    # try:
    #     for i in range(10):
    #         # await asyncio.sleep(1)
    #         time.sleep(2)
    #         a = random.randint(1,100)
    #         if a < 30:
    #             faces = a
    #         else:
    #             faces = ''
    #         print('faces:'+str(faces))
    # except Exception as e:
    #     faces = ''
    for i in range(10):
        if i>5:
            await asyncio.sleep(300)
        queue.put(i)

async def check_permit(websocket):
    while True:
        recv_str = await websocket.recv()
        cred_dict = recv_str.split(":")
        if cred_dict[0] == "admin" and cred_dict[1] == "123456":
            response_str = "congratulation, you have connect with server\r\nnow, you can do something else"
            await websocket.send(response_str)
            return True
        else:
            response_str = "sorry, the username or password is wrong, please submit again"
            await websocket.send(response_str)

# 接收客户端消息并处理，再返回回去
async def recv_msg(websocket):
    while True:
        recv_text = await websocket.recv()
        try:
            recv_text = recv_text.split('//')[-1].split('&')
            while True:
                #此处缺如何获取构建response_text数据的相关代码
                # 暂时写死，不确定客户端发送的数据，或者从其他地方调接口获取构建response_text的相关数据
                while queue.empty():
                    await asyncio.sleep(6)
                faces = queue.get()
                response_text = {"cameraId": recv_text[0].split('=')[-1],
                                 "data": [{"personId": recv_text[1].split('=')[-1], "img": recv_text[2].split('=')[-1]}
                                    ], "curTime": datetime.now().strftime('%H:%M,%Y/%m/%d'),'faces':faces}
                await asyncio.sleep(1)
                await websocket.send(json.dumps(response_text))
                if not response_text: #不断向客户端推送，直到response_text没有数据
                    break
        except Exception as e:
            print(e)
        response_text = 'data end'
        await websocket.send(response_text)
# 服务器端主逻辑
# websocket和path是该函数被回调时自动传过来的，不需要自己传
async def main_logic(websocket, path):
    await check_permit(websocket)

    await recv_msg(websocket)

def start_loop(loop,start_server):
    asyncio.set_event_loop(loop)
    loop.run_until_complete(start_server)
    loop.run_forever()
    # asyncio.get_event_loop().run_until_complete(start_server)
    # asyncio.get_event_loop().run_forever()


def run():
    # 把ip换成自己本地的ip
    start_server = websockets.serve(main_logic, '127.0.0.1', 5678)
    # 如果要给被回调的main_logic传递自定义参数，可使用以下形式
    # 一、修改回调形式
    # import functools
    # start_server = websockets.serve(functools.partial(main_logic, other_param="test_value"), '10.10.6.91', 5678)
    # 修改被回调函数定义，增加相应参数
    # async def main_logic(websocket, path, other_param)

    # 主线程中创建一个 new_loop
    new_loop = asyncio.get_event_loop()
    # 创建子线程 在其中开启无限事件循环
    t = Thread(target=start_loop,args=(new_loop,start_server))
    t.start()

    asyncio.run_coroutine_threadsafe(func(), new_loop)

if __name__ == '__main__':
    run()